package com.wf.course.web.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.utils.http.HttpRequest;
import com.utils.page.PageBean;
import com.wf.course.model.log.LoginLogs;
import com.wf.course.model.user.Role;
import com.wf.course.model.user.SysMenu;
import com.wf.course.model.user.User;
import com.wf.course.model.user.UserRoleRelation;
import com.wf.course.service.IRoleService;
import com.wf.course.service.ISysRoleMenuService;
import com.wf.course.service.IUserRoleRelationService;
import com.wf.course.service.IUserService;
import com.wf.course.web.Constants;
import com.wf.course.web.Interceptor.LogInfo;



@Controller
public class IndexController {

	@Autowired
	private IUserService iUserService;
	@Autowired
	private IUserRoleRelationService iUserRoleRelationService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private ISysRoleMenuService sysRoleMenuService;
	@Autowired
	private IUserRoleRelationService userRoleRelationService;
	
	@RequestMapping("/")
	public String index(HttpSession httpSession , Model model){

		// OSS访问地址放入全局
		Object oss = httpSession.getAttribute("WF_CONSOLE_CONFIG_OSS_URL");
		if(oss == null)
			httpSession.setAttribute("WF_CONSOLE_CONFIG_OSS_URL", Constants.OSSURL);

		if(!indexData(httpSession, model))
			return "login";
		return "index";
	}

	@RequestMapping("index")
	public String index_(HttpSession httpSession , Model model){
		if(!indexData(httpSession, model))
			return "login";
		return "index";
	}
	
	@RequestMapping("index_data")
	public String index_data(Model model){
		return "index_data";
	}
	
	/**
	 * 首页数据
	 * @param httpSession
	 * @param model
	 */
	private boolean indexData(HttpSession httpSession , Model model){
		Object token = httpSession.getAttribute("login_token");
		if(token != null){
			User user = Constants.LOGIN_USER.get(token.toString());
			if(user != null){
				model.addAttribute("userName", user.getUserName());
				return true;
			}
		}
		return false;
	}
	
	@RequestMapping(value="login" , method = RequestMethod.GET)
	public String login(){
		return "login";
	}
	
	@ResponseBody
	@RequestMapping(value = "login" ,method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public String login(@RequestParam String userName, @RequestParam String password , Model model , 
			HttpSession httpSession , HttpServletResponse response,HttpServletRequest request){
		User user = iUserService.login(userName, password);
		if(user != null && user.getPassword() != null){
			
			// 不允许登录
			if(!user.getStatus() ){
				LoginLogs log = new LoginLogs(user.getId(), HttpRequest.getRemoteAddress(request), HttpRequest.getMACAddress(request.getRemoteAddr()), false, userName + " : 该用户已经被禁用 ", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), null);
				 this.iUserService.addSysUserLogs(log);
				response.setStatus(HttpStatus.FORBIDDEN.value());
				return "";				
			}
			
			//获取角色信息
			List<UserRoleRelation> relations = iUserRoleRelationService.getByUserID(user.getId());
			if(relations != null && relations.size() > 0){
				
				// 如果不拥有内容管理权限 , 禁止登录
//				if(relations.stream().filter(r -> r.getRoleName().equals("manager")).count() == 0){
//					LoginLogs log = new LoginLogs(user.getId(), HttpRequest.getRemoteAddress(request), HttpRequest.getMACAddress(request.getRemoteAddr()), false, userName + " : 该用户没有权限登录本系统  ", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), null);
//					 this.iUserService.addSysUserLogs(log);
//					response.setStatus(HttpStatus.FORBIDDEN.value());
//					return "";
//				}
				
				//初始化角色集合
				user.setRoles(new ArrayList<>());
				for (UserRoleRelation relation : relations) {
					user.getRoles().add(new Role(relation.getRoleName()));
				}
				
				//将用户信息保存起来
				Constants.LOGIN_USER.put(user.getToken(), user);
				//将用户的唯一标识放入session
				httpSession.setAttribute("login_token", user.getToken());
				
				//查询用户的角色信息
				List<UserRoleRelation> userRole = iUserService.initUserRole(user.getId());
				//System.out.println("打印用户角色信息："+userRole.get(0).getRoleID());
				
				//查询用户角色对应的菜单信息
				List<SysMenu> sysMenuList = sysRoleMenuService.queryMenuByRoleId(userRole.get(0).getRoleID());
				//System.out.println("打印用户菜单信息："+sysMenuList.get(0).toString());
				
				httpSession.setAttribute("sysMenuList", sysMenuList);
				
				/**
				 * 添加登录日志
				 */
				LoginLogs log = new LoginLogs(user == null ? -1 : user.getId(), HttpRequest.getRemoteAddress(request),HttpRequest.getMACAddress(request.getRemoteAddr()), true, userName + " : 登录成功", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), null);
				 this.iUserService.addSysUserLogs(log);
				
				
				//返回状态码 200
				response.setStatus(HttpStatus.OK.value());
				return "";
			}else{
				LoginLogs log = new LoginLogs(user.getId(), HttpRequest.getRemoteAddress(request), HttpRequest.getMACAddress(request.getRemoteAddr()), false, userName + " : 该用户没有权限登录本系统  ", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), null);
				 this.iUserService.addSysUserLogs(log);
				response.setStatus(HttpStatus.FORBIDDEN.value());
				return "";
			}
		}
		
		/**
		 * 添加登录日志
		 */
		LoginLogs log = new LoginLogs(user == null ? -1 : user.getId(), HttpRequest.getRemoteAddress(request), HttpRequest.getMACAddress(request.getRemoteAddr()), false, userName + " : 用户名或密码错误", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), null);
		 this.iUserService.addSysUserLogs(log);
		
		//返回状态码401
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		
		return "";
	}
	//退出系统
	@RequestMapping("logout")
	public String logout(HttpSession httpSession){
		Object token = httpSession.getAttribute("login_token");
		if(token != null){
			//清空用户缓存
			Constants.LOGIN_USER.remove(token.toString());
			//清空token
			httpSession.setAttribute("login_token", null);
		}
		return "login";
	}
	
	/**
	 * 列表展示
	 * @param pageNo
	 * @param pageSize
	 * @param model
	 * @return
	 */
	@LogInfo("查询系统用户信息列表")
	@RequestMapping("sysUserList")
	public String sysUserList(HttpSession httpSession,
			@RequestParam(value = "pageNo", required = false) Integer pageNo,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "telephone", required = false) String telephone,
			Model model) {

		// 组装一个查询条件的map
		Map<String, Object> cons = new HashMap<String, Object>();
		cons.put("userName", userName);
		cons.put("telephone", telephone);
		PageBean<User> pageBean = new PageBean<User>(pageNo, pageSize, null, cons);
		pageBean.setUrl("/sysUserList");
		this.iUserService.indexInfo(pageBean);
		
		model.addAttribute("page", pageBean);
		//查询当前登录用户角色
		Object token = httpSession.getAttribute("login_token");
		User user = Constants.LOGIN_USER.get(token.toString());
		if(user != null){
			//查询用户角色:userRole
			List<UserRoleRelation>	userRoleRelations = userRoleRelationService.getByUserID(user.getId());
			if(userRoleRelations!=null && userRoleRelations.size()>0){
				model.addAttribute("userRole",  userRoleRelations.get(0).getRoleName());
			}
			 
		}
		
		return "sys/sysUserList";
	}

	/**
	 *  修改和新增页面数据初始化
	 * @param id
	 * @param model
	 * @return
	 */
	@LogInfo("新增或修改系统用户信息，页面数据初始化")
	@RequestMapping("pageLoad/{id}")
	public String downLoadById(HttpSession httpSession,@PathVariable("id") Integer id, Model model) {
		
		Object token = httpSession.getAttribute("login_token");
		User user = Constants.LOGIN_USER.get(token.toString());
		if(user != null){
			model.addAttribute("loginUser", user.getUserName());
			 
		}
		 
		if (id != null && id != 0) {
			User sysUser = iUserService.getById(id);
			model.addAttribute("sysUser", sysUser);
			model.addAttribute("type", "upd");
		}else{
			model.addAttribute("type", "add");
		}
		//查询用户角色:userRole
		List<UserRoleRelation>	userRoleRelations = userRoleRelationService.getByUserID(id);
		if(userRoleRelations!=null && userRoleRelations.size()>0){
			model.addAttribute("userRole",  userRoleRelations.get(0));
		}
		//查询角色列表
		List<Role> roles = roleService.queryRoles();
 		model.addAttribute("roles",  roles);
		
		return "sys/sysUserEdit";
	}

	/**
	 * 新增和修改
	 * @param SysUser
	 * @param request
	 * @return
	 */
	@LogInfo("新增或修改系统用户信息")
	@RequestMapping(value = "sysUserEdit" ,method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public String sysUserEdit(@ModelAttribute User user, String[] roleID ) {
		
 		iUserService.saveOrUpdateUser(user, roleID);
		
		return "redirect:/sysUserList";
	}
//
//	/**
//	 * 删除
//	 * @param id
//	 * @return
//	 */
//	@RequestMapping(value = "remove/{id}")
//	public String removeAd(@PathVariable("id") Integer id) {
//		
//		sysUserService.deleteById(id);
//		
//		return "redirect:/sysUser/sysUserList";
//	}
	
	/**
	 *  判断登录用户角色，如果是管理员，允许修改，其他不允许
	 * @param id
	 * @param model
	 * @return
	 */
	@LogInfo("更改系统用户状态")
	@RequestMapping("updateStatus/{id}")
	public String updateStatus(HttpSession httpSession,@PathVariable("id") Integer id, Model model) {
		
		Object token = httpSession.getAttribute("login_token");
		User user = Constants.LOGIN_USER.get(token.toString());
		if(user != null){
			//查询用户角色:userRole
			List<UserRoleRelation>	userRoleRelations = userRoleRelationService.getByUserID(user.getId());
			if(userRoleRelations!=null && userRoleRelations.size()>0){
				//判断用户角色是否是manager
				if(userRoleRelations.get(0).getRoleName().equals("manager")){
					User sysUser = iUserService.getById(id);
					Integer newStatus = 0;
					if(sysUser.getStatus()){
						newStatus = 0;
						
					}else{
						newStatus = 1;
					}
					iUserService.updateUserStatus(id,newStatus);
				}else{
					System.out.println("不是系统管理员，无权修改");
				}
				model.addAttribute("userRole",  userRoleRelations.get(0).getRoleName());
			}
		}
		 
		return "redirect:/sysUserList";
	}
	
}
